// 请求器实例，挂载于window._request
import axios from 'axios'
import qs from 'qs'

const userId = localStorage.getItem('user_id'),
token = localStorage.getItem('token')

var config = {
  timeout: 7000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'user-id': userId,
    token
  },

  transformRequest: qs.stringify
}

var axiosInstance = axios.create({
  baseURL: Vue._GLOBAL.api,
  ...config
})

axiosInstance.interceptors.request.use(requestDataHandler)
axiosInstance.interceptors.response.use(responseDataHandler)

// 请求拦截器
function requestDataHandler(req){
  var userId = localStorage.getItem('user_id')
  if(userId){
    if(req.method === 'post'){
      if(!req.data) req.data = {}
      req.data.city_id = typeof req.data.city_id === 'undefined' ? localStorage.getItem('selectedCityId') :
      req.data.city_id 
    }else{
      if(!req.params) req.params = {}
      req.params.city_id = typeof req.params.city_id === 'undefined' ? localStorage.getItem('selectedCityId') :
      req.params.city_id
    }
  }
  return req
}

// 响应拦截器
function responseDataHandler(res){

  return res.data
}


window._request = axiosInstance